/**
 * 界面通用顶部工具栏组件（左侧查询条件、右侧功能按钮）
 */
(function ($) {
    //高级查询中时间快捷选择事件（时间控件会自动填充相应数据）
    function changeDateLine(format, dataLineConfig) {
        $(this).addActiveClass();
        var val = $(this).attr('data-val');
        $(this).siblings('input[type=hidden]').val(val);

        if (!dataLineConfig) {
            return;
        }


        var now = new Date(),
            beginDate = new Date(),
            endDate;

        var $area = $(this).closest('.topBar').find('>.more-area');

        var $beginInput = $(':text[name=' + dataLineConfig.name1 + ']', $area),
            $endInput = $(':text[name=' + dataLineConfig.name2 + ']', $area);

        switch (val) {
            case '01'://今天
                endDate = beginDate;
                break;
            case '02'://昨天
                endDate = beginDate.dateAdd('d', -1);
                break;
            case '03'://近7天
                beginDate = beginDate.dateAdd('d', -7);
                endDate = now.dateAdd('d', -1);
                break;
            case '04'://本月
                beginDate = new Date(beginDate.getFullYear(), beginDate.getMonth(), 1);
                endDate = now.getDate() == 1 ? now : now.dateAdd('d', -1);
                break;
            case '05'://上月
                beginDate = new Date(beginDate.getFullYear(), beginDate.getMonth(), 1).dateAdd('m', -1);
                endDate = new Date(now.getFullYear(), now.getMonth(), 1).dateAdd('d', -1);
                break;
            case '06'://今年
                beginDate = new Date(now.getFullYear(), 0, 1);
                endDate = now.getDate() == 1 ? now : now.dateAdd('d', -1);
                break;
            case '07'://去年
                beginDate = new Date(now.getFullYear() - 1, 0, 1);
                endDate = new Date(now.getFullYear() - 1, 11, 31);
                break;
            default://自定义
                endDate = beginDate;
                break;
        }
        $beginInput.val(beginDate.format(format));
        endDate.setHours(23, 59, 59);
        $endInput.val(endDate.format(format));
    }

    //创建文本输入栏
    function createText(item) {
        var $li = $('<li class="item"><label class="label-text">{0}：</label></li>'.format(item.text));

        var $input = $('<input class="input-text" type="text" placeholder="" name="{0}" {1}>'.format(item.name, item.id ? ('id="' + item.id + '"') : '')).appendTo($li);
        $input.width(item.width || 80);
        return $li;
    }

    //创建文本输入弹出树型选择栏
    function createTextTree(item) {
        var $li = createText(item);
        $li.find(':text').attr('readonly', true).removeAttr('name').data('data-options', item.option);
        $li.css('position', 'relative').append('<span class="inner-icon-tree"></span>');
        $li.append('<input type="hidden" name="{0}">'.format(item.name));
        $li.on('click', function () {
            var $text = $(':text', this);
            commonFun.execParentMethod('treeDialog', $text.data('data-options'), $text);
        });
        return $li;
    }

    //报表时间快捷切换事件
    function reportDateSelectChange(el) {
        $(el).on('click', 'a', function () {
            if (!$(this).hasClass('active')) {
                $(this).addActiveClass();
                pickerChange($(this).attr('data-val'), $(this).parent().data('data-targetId'));
            }
        });
        setTimeout(function () {
            var $a = $(el).find('a:eq(0)');
            $a.trigger('click');
            $('#' + $a.parent().data('data-targetId')).val(new Date().format());
        }, 100);

        function pickerChange(val, targetId) {
            var $beginDate = $('#' + targetId);
            $beginDate.val('').unbind('focus');
            switch (val) {
                case '1':
                    $beginDate.on('focus', function () {
                        WdatePicker({
                            dateFmt: 'yyyy-MM-dd',
                            firstDayOfWeek: 1,
                            isShowClear: false,
                            onpicked: function () {
                                this.blur();
                            }
                        })
                    });
                    break;
                case '2':
                    $beginDate.on('focus', function () {
                        WdatePicker({
                            dateFmt: 'yyyy-WW周（yyyy-MM-dd~yyyy-MM-dd）',
                            firstDayOfWeek: 1,
                            isShowWeek: true,
                            isShowClear: false,
                            errDealMode: 2,
                            onpicked: function () {
                                var y = $dp.cal.getP('y'); //年
                                var m = $dp.cal.getP('M');//月
                                var d = $dp.cal.getP('d');//日
                                var W = $dp.cal.getP('W');//第几周
                                var w = $dp.cal.getP('w');//星期

                                var chooseDate = new Date(y + '/' + m + '/' + d);
                                var monday = new Date(chooseDate.setDate(chooseDate.getDate() - w + 1));
                                var sunday = new Date(chooseDate.setDate(chooseDate.getDate() + 6));

                                this.blur();
                                if (monday.getFullYear() != sunday.getFullYear()) {
                                    if (W === '01') {
                                        y = sunday.getFullYear();
                                    } else {
                                        y = monday.getFullYear();
                                    }
                                }
                                var str = y + '-' + W + '周' + '（' + monday.format() + '~' + sunday.format() + '）';
                                $(this).val(str);

                                $(this).removeClass('WdateFmtErr');
                            }
                        })
                    });
                    break;
                case '3':
                    $beginDate.on('focus', function () {
                        WdatePicker({
                            autoShowQS: true,
                            firstDayOfWeek: 1,
                            dateFmt: 'yyyy-MM月',
                            isShowClear: false,
                            onpicked: function () {
                                this.blur();
                            }
                        })
                    });
                    break;
                case '4':
                    $beginDate.on('focus', function () {
                        WdatePicker({
                            autoShowQS: true,
                            isShowClear: false,
                            dateFmt: 'yyyy-MM季',
                            firstDayOfWeek: 1,
                            isQuarter: true,
                            isShowOK: true,
                            isShowToday: false,
                            autoPickDate: false,
                            disabledDates: ['....-0[5-9]-..', '....-1[0-2]-..'],
                            startDate: '%y-01-01',
                            errDealMode: 1,
                            onpicked: function () {
                                this.blur();
                            }
                        })
                    });
                    break;
                case '5':
                    $beginDate.on('focus', function () {
                        WdatePicker({
                            autoShowQS: true,
                            isShowClear: false,
                            firstDayOfWeek: 1,
                            dateFmt: 'yyyy年',
                            isShowToday: false,
                            onpicked: function () {
                                this.blur();
                            }
                        })
                    });
                    break;
            }
        }
    }

    //创建下拉选择组件（数据来源于缓存、配置、后台实时查询）
    function createSelect(item) {
        var $li = $('<li class="item"><label class="label-text">{0}：</label></li>'.format(item.text));
        var arr = [];
        if (item.dict) {
            var dictArr = window.parent.GLOBAL_PARAMS.DICT_CACHE[item.dict];
            dictArr && $.each(dictArr, function (index, item) {

                arr.push(item);
            });
        }

        item.data && $.each(item.data, function (index, item) {
            arr.push({key: item.value, value: item.text});
        });

        var selectHtml = '<select name="{0}" {1}>'.format(item.name, item.width ? ('style="width:' + item.width + 'px;"') : '');
        if (item.showEmpty === undefined) {
            item.showEmpty = true;
        }
        if (item.showEmpty) {
            selectHtml += '<option value="{0}">{1}</option>'.format('', '请选择');
        }
        $.each(arr, function (index, item) {
            selectHtml += '<option value="{0}">{1}</option>'.format(item.key, item.value);
        });
        selectHtml += '</select>';
        $(selectHtml).appendTo($li).select2();

        return $li;
    }

    function createBtn(item) {
        var $li = $('<li class="item"><a class="btn btn-overlay" >{0}</a></li>'.format(item.text));
        var $a = $('>a', $li).on('click', function () {
            item.click.call(this);
        });
        if (item.css) {
            $a.addClass(item.css);
        }
        return $li;
    }

    /**
     * 加载Select后台数据
     * @param url
     * @param params
     * @param fn
     */
    function loadSelectData(url, params, fn) {
        $.ajaxExt({
            url: url,
            data: params || {},
            success: function (data) {
                data && fn && fn(data);
            }
        })
    }

    /**
     * 根据类型返回时间类型选择的HTML
     * @param type
     * @returns {string}
     */
    function getDateTypeHtml(type) {
        var html = '<div class="time-select clearfix"><input type="hidden" name="dateType">';
        if (type === 'custom') {
            html += [
                '<a data-val="01">今天</a>',
                '<a data-val="02">昨天</a>',
                '<a data-val="03">近7天</a>',
                '<a data-val="04">本月</a>',
                '<a data-val="05">上月</a>'].join('');//去除了自定义
        } else {
            html += [
                '<a data-val="02">昨天</a>',
                '<a data-val="03">近7天</a>',
                '<a data-val="04">本月</a>',
                '<a data-val="05">上月</a>',
                '<a data-val="06">今年</a>',
                '<a data-val="07">去年</a>'].join('');
        }
        html += '</div>';
        return html;
    }


    var _dateTextPrefix = '_top_date_', _dateIndex = 0;

    $.canui('topBar', {
        options: {
            left: [],//左侧区域配置
            right: null//右侧区域配置
        },
        _filterMore: null,
        _dateLineFormat: 'yyyy-MM-dd',//时间快捷中时间的格式
        _create: function () {
            var _t = this;

            if (_t.element.parent().attr('data-layout')) {
                _t.layout = true;
            }
            _t._createLeft();
            _t._createRight();
        },
        _dateLineConfig: null,
        /**
         * 创建组件左侧区域
         * @private
         */
        _createLeft: function () {
            var _t = this;
            this.element.addClass('fliter-box2-pa');

            //创建高级查询区域
            function createFilterMore(item, search, dateType, showToggleBtn) {
                var _html = '';

                //如果长度大于1的话说明要显示高级查询伸缩的按钮
                if (showToggleBtn) {
                    _html = '<div class="filter-more"><p class="text">高级查询</p></div>';
                }

                _html += getDateTypeHtml(dateType);
                var _$con = $(_html);

                _t._filterMore = $('<div class="more-area" style="margin-top: 10px;visibility: hidden;position: absolute; width: 100%;box-sizing: border-box;"><ul></ul></div>');
                //点击高级查询按钮切换高级查询搜索条件显示隐藏
                $(_$con.filter('.filter-more')).on('click', function (e) {
                    var el = e.target || e.srcElement;
                    if (el.tagName === 'P') {
                        var addHeight = 44;
                        if (!$(this).hasClass('filter-more-active')) {
                            addHeight = 44 + _t._filterMore.outerHeight() + 10;
                        }
                        $(this).toggleClass('filter-more-active');


                        var $parent = _t.element.parent();
                        if (addHeight > 44) {
                            _t._filterMore.css('visibility', 'visible');
                        }
                        $parent.stop().animate({
                            height: addHeight
                        }, {
                            speed: 100,
                            step: function () {
                                if (_t.layout) {
                                    $parent.trigger('can-resize', true);
                                }
                            },
                            complete: function () {
                                if (addHeight <= 44) {
                                    _t._filterMore.css('visibility', 'hidden');
                                }
                            }
                        });
                    }
                });


                var _$ul = $('ul', _t._filterMore);
                //查询过滤条件组件的拼装
                $.each(item, function (i, t) {
                    _$ul.append(_t._createSearchItem(t, true));
                });

                //高级搜索查询中的查询按钮事件绑定
                if (showToggleBtn) {
                    $('<li class="li-item clearfix pt10 btn-overlay"><a class="search-btn">查询</a></li>').appendTo(_$ul).on('click', 'a', function () {
                        var $area = $(this).closest('.more-area');
                        var values = $area.getValues();
                        //if (_t._dateLineConfig) {
                        //    if (!values[_t._dateLineConfig.name1]) {
                        //        $(':text[name=' + _t._dateLineConfig.name1 + ']', $area).trigger('focus');
                        //    }
                        //    if (!values[_t._dateLineConfig.name2]) {
                        //        $(':text[name=' + _t._dateLineConfig.name2 + ']', $area).trigger('focus');
                        //    }
                        //}
                        search.call($area, values);
                    });
                }

                _t._filterMore.insertAfter(_t.element);

                _$con.appendTo(_t.element);

                //点击时间快捷事件

                var $timeSelect = $(_$con.filter('.time-select')).on('click', 'a', function () {
                    changeDateLine.call(this, _t._dateLineFormat, _t._dateLineConfig);
                    var $area = $(this).closest('.topBar').find('.more-area');
                    $area.length && search.call($area, $area.getValues());
                });

                if (dateType === 'custom') {

                    var $beginInput = $(':text[name=' + _t._dateLineConfig.name1 + ']', _t._filterMore),
                        $endInput = $(':text[name=' + _t._dateLineConfig.name2 + ']', _t._filterMore);

                    $beginInput.on('focus', function () {
                        WdatePicker({
                            dateFmt: _t._dateLineFormat,
                            minDate: '#F{$dp.$D(\'' + $endInput.attr('id') + '\',{d:-89});}',
                            maxDate: '#F{$dp.$D(\'' + $endInput.attr('id') + '\',{d:0});}',
                            onpicked: function () {
                                $timeSelect.find('>a.active').removeClass('active');
                            }
                        });
                    });
                    $endInput.on('focus', function () {
                        WdatePicker({
                            dateFmt: _t._dateLineFormat,
                            minDate: '#F{$dp.$D(\'' + $beginInput.attr('id') + '\',{d:0});}',
                            maxDate: '%y-%M-%d %H:%m:%s',
                            onpicked: function () {
                                $timeSelect.find('>a.active').removeClass('active');
                            }
                        });
                    });
                }

            }

            function createFilter(item, search) {
                _t.element.css({
                    'padding': '12px 15px 0',
                    height: 'auto'
                });
                var _$ul = $('<ul class="more-area"></ul>').appendTo(_t.element);
                $.each(item, function (i, t) {
                    _$ul.append(_t._createSearchItem(t));
                });

                $('<li class="li-item clearfix pt10 btn-overlay"><a class="search-btn">查询</a></li>').appendTo(_$ul).on('click', 'a.search-btn', function () {
                    var $area = $(this).closest('.more-area');
                    search.call($area, $area.getValues());
                });
            }


            //创建左侧普通查询输入组件栏
            (function () {
                var $con = $('<div class="fliter-box2" style="float: left;"><ul></ul></div>'),
                    $ul = $('>ul', $con);

                if (_t.options.left) {
                    $.each(_t.options.left, function (index, item) {

                        switch (item.type) {
                            case 'filter-more':

                                var showToggleBtn = true;
                                if (item.item && item.item.length == 1 && item.item[0].hidden) {
                                    showToggleBtn = false;
                                }

                                createFilterMore(item.item, item.search, item.dateType, showToggleBtn);
                                break;
                            case 'filter':
                                createFilter(item.item, item.search);
                                break;
                            case 'text':
                                $ul.append(createText(item));
                                break;
                            case 'text-tree':
                                $ul.append(createTextTree(item));
                                break;
                            case 'select':
                                $ul.append(createSelect(item));
                                break;
                            case 'btn':
                                $ul.append(createBtn(item));
                                break;
                        }

                        if ($ul[0].hasChildNodes()) {
                            _t.element.append($con);
                        }
                    });
                }
            })();

        },
        /**
         * 创建高级查询区域中的查询组件区域
         * @param op 查询条件配置，主要包括时间快捷组件、item-select组件等
         * @param hasTimeQuick 组件中是否包含时间快捷
         * @returns {jQuery}
         * @private
         */
        _createSearchItem: function (op, hasTimeQuick) {
            var _t = this;
            var $item = $('<li class="li-item"><label class="label-text">' + op.text + '：</label></li>');
            switch (op.type) {
                case 'dateLine':
                    if (op.format) {
                        _t._dateLineFormat = op.format;
                    }

                    if (op.hidden) {
                        $(['<input type="text" name="{0}">'.format(op.name1), '<input type="text" name="{0}">'.format(op.name2)].join('')).appendTo($item);
                        $item.hide().removeClass();
                    } else {
                        $(['<div class="date-input mt5">',
                            '<input type="text" name="{0}" readonly placeholder="请选择开始时间" id="{1}">'.format(op.name1, _dateTextPrefix + (_dateIndex++)),
                            '<span class="icon-dao">到</span>',
                            '<input type="text" name="{0}" readonly placeholder="请选择结束时间" class="ml15" id="{1}">'.format(op.name2, _dateTextPrefix + (_dateIndex++)),
                            '<span class="icon-date"></span>',
                            '<span class="icon-date icon-date-s"></span>',
                            '</div>'].join('')).appendTo($item);
                        if (!hasTimeQuick) {
                            var $beginInput = $(':text[name=' + op.name1 + ']', $item),
                                $endInput = $(':text[name=' + op.name2 + ']', $item);
                            $beginInput.on('focus', function () {
                                WdatePicker({
                                    dateFmt: op.format,
                                    maxDate: '#F{$dp.$D(\'' + $endInput.attr('id') + '\',{d:0});}'
                                });
                            });
                            $endInput.on('focus', function () {
                                WdatePicker({
                                    dateFmt: op.format,
                                    minDate: '#F{$dp.$D(\'' + $beginInput.attr('id') + '\',{d:0});}',
                                    maxDate: '%y-%M-%d %H:%m:%s'
                                });
                            });
                        }
                    }
                    _t._dateLineConfig = op;
                    break;
                case 'reportDateSelect':
                    var $itemSelect = $('<div class="element-select" name="' + op.name + '"></div>');
                    $.each([{value: '1', text: '日'}, {value: '2', text: '周'}, {value: '3', text: '月'}, {
                        value: '4',
                        text: '季度'
                    }, {value: '5', text: '年'}], function (i, val) {
                        $itemSelect.append('<a data-val="' + (val.value || '') + '" ' + '>' + val.text + '</a>');
                    });
                    $item.append($itemSelect);
                    $itemSelect.data('data-targetId', op.targetId);
                    reportDateSelectChange($itemSelect);
                    break;
                case 'item-select':
                    var $itemSelect = $('<div class="element-select" name="' + op.name + '"></div>');
                    if (op.data) {
                        $.each(op.data, function (i, val) {
                            $itemSelect.append('<a data-val="' + (val.value || '') + '" ' + (val.selected ? 'class="active"' : '') + '>' + val.text + '</a>');
                        });
                    }

                    if (op.url) {
                        loadSelectData(op.url, op.params, function (data) {
                            $.each(data, function (i, val) {
                                $itemSelect.append('<a data-val="{0}">{1}</a>'.format(val[op.key] || '', val[op.value] || ''));
                            });
                        });
                    }

                    if (op.dict) {
                        var dict = window.parent.GLOBAL_PARAMS.DICT_CACHE[op.dict];
                        if (op.extraData) {
                            $.each(op.extraData, function (i, val) {
                                $itemSelect.append('<a data-val="' + (val.value || '') + '" ' + (val.selected ? 'class="active"' : '') + '>' + val.text + '</a>');
                            });
                        }
                        $.each(dict, function (i, val) {
                            $itemSelect.append('<a data-val="{0}" class="{1}">{2}</a>'.format(val.key, val.wthrDefault === '1' ? 'active' : '', val.value));
                        });
                    }
                    if (!$('>.active', $itemSelect).length) {
                        $('>a:eq(0)', $itemSelect).addClass('active');
                    }
                    $item.append($itemSelect);
                    break;
                case 'text':
                    $item = (createText(op).attr('class', 'li-item'));//外层li的样式由item改成li-item
                    break;
                case 'text-tree':
                    $item = (createTextTree(op).attr('class', 'li-item'));
                    break;
                case 'select':
                    $item = (createSelect(op).attr('class', 'li-item'));
                    break;
                case 'btn':
                    $item = (createBtn(op).attr('class', 'li-item'));
                    break;
            }

            op.type === 'item-select' && $('.element-select', $item).on('click', 'a', function () {
                $(this).addActiveClass();
            });
            return $item;
        },
        /**
         * 创建右侧按钮栏，主要包含普通按钮、下拉按钮(导入导出)等
         * @private
         */
        _createRight: function () {
            var _t = this;
            if (_t.options.right) {
                var $right = $('<div class="operate-group clearfix"></div>');
                $.each(_t.options.right, function (index, item) {
                    var create = true;
                    //权限按钮，没有权限就不创建此按钮
                    if (item.authority && window.parent.GLOBAL_PARAMS.AUTHORITY_CACHE.indexOf(item.authority) == -1) {
                        create = false;
                    }
                    if (create) {
                        var _$btn;
                        if (item.type == 'export-btn') {
                            if (item.item) {
                                _$btn = $('<div class="btn btn-green slide-down-btn">' + item.text + '<ul></ul></div>');
                                $.each(item.item, function (i, t) {
                                    $('<li><a class="btn-overlay">' + t.text + '</a></li>').appendTo($('ul', _$btn)).on('click', function () {
                                        t.click();
                                    });
                                });
                                _$btn.on('click', function () {
                                    $('>ul', $(this)).toggle();
                                });
                                _$btn.appendTo($right);
                            }
                        } else if (item.type === 'btn') {
                            _$btn = $('<a class="btn btn-overlay">' + item.text + '</a>').appendTo($right).on('click', function () {
                                item.click();
                            });
                        }
                        if (index) {
                            _$btn.css('margin-right', 5);
                        }
                    }
                });
                var $moreArea = $('.more-area', _t.element);
                if ($moreArea.length && $moreArea[0].tagName === 'UL') {//暂时以样式为more-area且tagName为ul的来区分有没有高级搜索（包括时间快捷等）这一栏
                    $right.css({
                        float: 'right'
                    });
                    $('li:last', $moreArea).append($right);
                } else {
                    _t.element.append($right);
                }
            }
        },
        getDateType: function () {
            return $('input[type=hidden]', this.element).val();
        },
        getBeginEndTime: function () {
            var _t = this;
            var $area = $(_t.element).closest('.topBar').find('>.more-area');
            var beginName = _t._dateLineConfig.name1,
                endName = _t._dateLineConfig.name2;
            var $beginInput = $(':text[name=' + beginName + ']', $area),
                $endInput = $(':text[name=' + endName + ']', $area);

            var ret = {};
            ret[beginName] = $beginInput.val();
            ret[endName] = $endInput.val();
            return ret;
        }
    });
})(jQuery);